package com.anonymous.community.ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.anonymous.community.AdminActivity;
import com.anonymous.community.LoginActivity;
import com.anonymous.community.api.ApiClient;
import com.anonymous.community.api.ApiService;
import com.anonymous.community.api.model.GenericResponse;
import com.anonymous.community.databinding.FragmentActivityBinding;
import com.anonymous.community.ui.base.BaseFragment;
import com.anonymous.community.utils.TokenManager;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 个人中心Fragment
 * 显示用户信息和设置选项
 */
public class ActivityFragment extends BaseFragment {

    private FragmentActivityBinding binding;
    private ApiService apiService;
    private TokenManager tokenManager;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentActivityBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        apiService = ApiClient.getApiService();
        tokenManager = new TokenManager(requireContext());

        setupViews();
        loadUserInfo();

        return root;
    }

    private void setupViews() {
        // 登出按钮
        binding.btnLogout.setOnClickListener(v -> showLogoutDialog());

        // 删除账户按钮
        binding.btnDeleteAccount.setOnClickListener(v -> showDeleteAccountDialog());

        // 取消删除按钮
        binding.btnCancelDelete.setOnClickListener(v -> cancelDeleteAccount());

        // 管理员入口（仅管理员可见）
        String role = tokenManager.getUserRole();
        if ("admin".equals(role) || "super_admin".equals(role)) {
            binding.btnAdminPanel.setVisibility(View.VISIBLE);
            binding.btnAdminPanel.setOnClickListener(v -> {
                Intent intent = new Intent(requireContext(), AdminActivity.class);
                startActivity(intent);
            });
        } else {
            binding.btnAdminPanel.setVisibility(View.GONE);
        }
    }

    /**
     * 加载用户信息
     */
    private void loadUserInfo() {
        String username = tokenManager.getUsername();
        String role = tokenManager.getUserRole();
        int userId = tokenManager.getUserId();

        if (username != null) {
            binding.tvUsername.setText(username);
        } else {
            binding.tvUsername.setText("未登录");
        }

        if (role != null) {
            binding.tvRole.setText(getRoleText(role));
        } else {
            binding.tvRole.setText("普通用户");
        }

        binding.tvUserId.setText("ID: " + userId);
    }

    /**
     * 获取角色文本
     */
    private String getRoleText(String role) {
        switch (role) {
            case "super_admin":
                return "超级管理员";
            case "admin":
                return "管理员";
            case "user":
            default:
                return "普通用户";
        }
    }

    /**
     * 显示登出确认对话框
     */
    private void showLogoutDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("确认登出")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> performLogout())
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 执行登出
     */
    private void performLogout() {
        String token = TokenManager.getToken(requireContext());
        if (token != null && !token.isEmpty()) {
            binding.progressBar.setVisibility(View.VISIBLE);
            
            apiService.logout(token)
                    .enqueue(new Callback<GenericResponse>() {
                        @Override
                        public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
                            binding.progressBar.setVisibility(View.GONE);
                            
                            // 无论API调用成功与否，都清除本地token
                            TokenManager.clearToken(requireContext());
                            
                            // 跳转到登录页
                            Intent intent = new Intent(requireActivity(), LoginActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                            requireActivity().finish();
                        }

                        @Override
                        public void onFailure(Call<GenericResponse> call, Throwable t) {
                            binding.progressBar.setVisibility(View.GONE);
                            
                            // 即使网络失败也清除本地token
                            TokenManager.clearToken(requireContext());
                            
                            Intent intent = new Intent(requireActivity(), LoginActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                            requireActivity().finish();
                        }
                    });
        } else {
            // 没有token，直接跳转登录页
            Intent intent = new Intent(requireActivity(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            requireActivity().finish();
        }
    }

    /**
     * 显示删除账户确认对话框
     */
    private void showDeleteAccountDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("删除账户")
                .setMessage("账户将在7天后永久删除\n删除期间可以取消\n确定要申请删除吗？")
                .setPositiveButton("确定", (dialog, which) -> requestDeleteAccount())
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 申请删除账户
     */
    private void requestDeleteAccount() {
        String token = TokenManager.getToken(requireContext());
        if (token == null || token.isEmpty()) {
            Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        binding.progressBar.setVisibility(View.VISIBLE);
        
        apiService.manageAccount(token)
                .enqueue(new Callback<GenericResponse>() {
                    @Override
                    public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
                        binding.progressBar.setVisibility(View.GONE);
                        
                        if (response.isSuccessful() && response.body() != null) {
                            Toast.makeText(requireContext(), "账户删除申请成功，将在7天后永久删除", Toast.LENGTH_LONG).show();
                            binding.btnCancelDelete.setVisibility(View.VISIBLE);
                        } else {
                            String errorMsg = extractErrorMessage(response);
                            Toast.makeText(requireContext(), 
                                errorMsg != null ? errorMsg : "申请失败", 
                                Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<GenericResponse> call, Throwable t) {
                        binding.progressBar.setVisibility(View.GONE);
                        Toast.makeText(requireContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 取消删除账户
     */
    private void cancelDeleteAccount() {
        String token = TokenManager.getToken(requireContext());
        if (token == null || token.isEmpty()) {
            Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        binding.progressBar.setVisibility(View.VISIBLE);
        
        apiService.confirmCancelDelete(token)
                .enqueue(new Callback<GenericResponse>() {
                    @Override
                    public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
                        binding.progressBar.setVisibility(View.GONE);
                        
                        if (response.isSuccessful() && response.body() != null) {
                            Toast.makeText(requireContext(), "已取消删除申请", Toast.LENGTH_SHORT).show();
                            binding.btnCancelDelete.setVisibility(View.GONE);
                        } else {
                            String errorMsg = extractErrorMessage(response);
                            Toast.makeText(requireContext(), 
                                errorMsg != null ? errorMsg : "取消失败", 
                                Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<GenericResponse> call, Throwable t) {
                        binding.progressBar.setVisibility(View.GONE);
                        Toast.makeText(requireContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 提取错误信息
     */
    private String extractErrorMessage(Response<?> response) {
        try {
            if (response != null && response.errorBody() != null) {
                String raw = response.errorBody().string();
                if (raw != null && !raw.isEmpty()) {
                    try {
                        org.json.JSONObject obj = new org.json.JSONObject(raw);
                        if (obj.has("error")) {
                            return obj.optString("error");
                        }
                    } catch (Exception jsonEx) {
                        return raw;
                    }
                }
            }
        } catch (Exception e) {
            // 忽略
        }
        return null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    protected String getPageName() {
        return "个人中心";
    }
}
